package cn.com.lyj6851.modules.mp.handler;

import cn.com.lyj6851.modules.mp.domain.YdyWechatReply;
import cn.com.lyj6851.modules.mp.service.YdyWechatReplyService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private YdyWechatReplyService ydyWechatReplyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {


        String str = "你好，欢迎关注一点语教育";
        YdyWechatReply wechatReply = ydyWechatReplyService.isExist("subscribe");
        if(!ObjectUtil.isNull(wechatReply)){
            // 如果数据库有回复内容转换成字符串
            str = JSONObject.parseObject(wechatReply.getData()).getString("content");
        }
        try {// 执行发送
            WxMpXmlOutMessage msg= WxMpXmlOutMessage.TEXT()
                    .content(str)
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .build();
            return msg;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }
}
